import time
import requests

# from common.handle_redis import RedisHelper
from perf_settings import *
from common.hande_device import HandleDevices
from influxdb_client import Point

from common.handle_influxdb import InfluxDBHandler

do_devices = HandleDevices(pkgName=MID_pkgName)
do_influxdb = InfluxDBHandler()
# do_redis = RedisHelper(host="116.62.245.174", port="6379", password="li123456")
apm_pid_main = do_devices.handle_main_device(deviceId_001=deviceId_001)
if Secondary_device:
    apm_pid_sec = do_devices.handle_sec_device(deviceId_002=deviceId_002)
# do_redis.set(key="stop_HQ", value=False, ex="86400")
while True:
    # 准备数据点列表
    try:
        if Secondary_device:
            time.sleep(2)
            device_001_cpu = do_devices.get_cpu(apm_pid_main)
            device_001_app_mem = do_devices.get_mem(apm_pid_main)
            device_001_sys_mem = do_devices.get_sys_mem(apm_pid_main)
            #
            device_002_cpu = do_devices.get_cpu(apm_pid_sec)
            device_002_app_mem = do_devices.get_mem(apm_pid_sec)
            device_002_sys_mem = do_devices.get_sys_mem(apm_pid_sec)

            measurements = [
                Point("device_001").tag("pid", "main_pid").field("cpu", device_001_cpu["appCpuRate"]),
                Point("device_001").tag("pid", "main_pid").field("mem", device_001_app_mem),
                Point("device_001").tag("pid", "system").field("cpu", device_001_cpu["systemCpuRate"]),
                Point("device_001").tag("pid", "system").field("mem", device_001_sys_mem),

                # 分割
                Point("device_002").tag("pid", "main_pid").field("cpu", device_002_cpu["appCpuRate"]),
                Point("device_002").tag("pid", "main_pid").field("mem", device_002_app_mem),
                Point("device_002").tag("pid", "system").field("cpu", device_002_cpu["systemCpuRate"]),
                Point("device_002").tag("pid", "system").field("mem", device_002_sys_mem),
            ]
        else:
            time.sleep(2)
            device_001_cpu = do_devices.get_cpu(apm_pid_main)
            device_001_app_mem = do_devices.get_mem(apm_pid_main)
            device_001_sys_mem = do_devices.get_sys_mem(apm_pid_main)
            measurements = [
                Point("device_001").tag("pid", "main_pid").field("cpu", device_001_cpu["appCpuRate"]),
                Point("device_001").tag("pid", "main_pid").field("mem", device_001_app_mem),
                Point("device_001").tag("pid", "system").field("cpu", device_001_cpu["systemCpuRate"]),
                Point("device_001").tag("pid", "system").field("mem", device_001_sys_mem),
            ]
        do_influxdb.write_mul_data(measurements=measurements)
    except:
        # do_redis.set(key="stop_HQ", value="True", ex="86400")
        requests.get(url="https://api.day.app/s3KoLFVvWVWdYiiro2gKW/多屏1.0性能采集可能出现问题")
